﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using Zhaoxi.ReadWriteSeparation.Interface;
using Zhaoxi.ReadWriteSeparation.Model;

namespace Zhaoxi.ReadWriteSeparation.Service
{
    public class UserService : IUserService
    {
        private DbContext _dbContext = null;
        public UserService(DbContext dbContext)
        {
            this._dbContext = dbContext;
        }

        public User FindUser(int id)
        {
            this._dbContext = this._dbContext.ToRead();
            User user = this._dbContext.Set<User>().Where(u => u.Id == id).FirstOrDefault();

            #region 打印下链接
            string conn = this._dbContext.Database.GetDbConnection().ConnectionString;
            Console.WriteLine($"This is {conn}....Find");
            if (user != null)
                user.CompanyName = conn;//返回请求地址
            #endregion
            return user;
        }

        public User InsertUser(User user)
        {
            _dbContext = this._dbContext.ToWrite();
            _dbContext.Set<User>().Add(user);
            _dbContext.SaveChanges();

            #region 打印下链接
            string conn = this._dbContext.Database.GetDbConnection().ConnectionString;
            Console.WriteLine($"This is {conn}....InsertUser");
            user.CompanyName = conn;
            #endregion
            return user;
        }
    }
}
